#include "lvgl/lvgl.h"
#include "lvgl/demos/lv_demos.h"
#include "lv_drivers/display/fbdev.h"
#include "lv_drivers/indev/evdev.h"
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>

#include "./../../inc/homepage.h"
#include "./../../inc/msg_popup.h"
#include "./../../inc/cJSON.h"
#include "./../../inc/user_event.h"
#include "./../../inc/tcp.h"

// 解析好友列表JSON数据 指针传递
void parse_friend_list(const char * response, FriendList_t * friendList)
{
    // 校验输入参数
    if(response == NULL || strlen(response) == 0) {
        printf("无效的响应数据\n");
        return;
    }

    if(friendList == NULL) {
        printf("好友列表指针不能为空\n");
        return;
    }

    // 初始化结构体，避免残留数据
    memset(friendList, 0, sizeof(FriendList_t));

    // 解析JSON根对象
    cJSON * root = cJSON_Parse(response);
    if(root == NULL) {
        printf("JSON解析失败: %s\n", cJSON_GetErrorPtr());
        return;
    }

    // 检查code是否为0（成功状态）
    cJSON * code = cJSON_GetObjectItem(root, "code");
    if(code == NULL || code->valueint != 0) {
        cJSON * msg = cJSON_GetObjectItem(root, "message");
        printf("获取好友列表失败: %s\n", (msg != NULL) ? msg->valuestring : "未知错误");
        cJSON_Delete(root);
        return;
    }

    // 获取payload对象
    cJSON * payload = cJSON_GetObjectItem(root, "payload");
    if(payload == NULL || !cJSON_IsObject(payload)) {
        printf("未找到有效的payload数据\n");
        cJSON_Delete(root);
        return;
    }

    // 解析userid
    cJSON * userid = cJSON_GetObjectItem(payload, "userid");
    if(userid != NULL && cJSON_IsString(userid) && strlen(userid->valuestring) > 0) {
        strncpy(friendList->userid, userid->valuestring, sizeof(friendList->userid) - 1);
        friendList->userid[sizeof(friendList->userid) - 1] = '\0'; // 确保字符串终止
    }

    // 解析friend_list数组
    cJSON * friend_array = cJSON_GetObjectItem(payload, "friend_list");
    if(friend_array != NULL && cJSON_IsArray(friend_array)) {
        friendList->friend_count = cJSON_GetArraySize(friend_array);

        // 分配好友信息数组内存
        if(friendList->friend_count > 0) {
            friendList->friends = (FriendInfo *)malloc(sizeof(FriendInfo) * friendList->friend_count);
            if(friendList->friends == NULL) {
                printf("内存分配失败\n");
                cJSON_Delete(root);
                friendList->friend_count = 0; // 重置计数
                return;
            }

            // 遍历好友数组
            for(int i = 0; i < friendList->friend_count; i++) {
                // 初始化每个好友信息结构
                memset(&friendList->friends[i], 0, sizeof(FriendInfo));

                cJSON * friend_item = cJSON_GetArrayItem(friend_array, i);
                if(friend_item == NULL || !cJSON_IsObject(friend_item)) {
                    continue;
                }

                // 解析好友ID
                cJSON * db_id = cJSON_GetObjectItem(friend_item, "friend_db_id");
                if(db_id != NULL && cJSON_IsNumber(db_id)) {
                    friendList->friends[i].friend_db_id = db_id->valueint;
                }

                // 解析好友名称
                cJSON * name = cJSON_GetObjectItem(friend_item, "friend_name");
                if(name != NULL && cJSON_IsString(name) && strlen(name->valuestring) > 0) {
                    strncpy(friendList->friends[i].friend_name, name->valuestring,
                            sizeof(friendList->friends[i].friend_name) - 1);
                    friendList->friends[i].friend_name[sizeof(friendList->friends[i].friend_name) - 1] = '\0';
                }

                // 解析好友userid
                cJSON * f_userid = cJSON_GetObjectItem(friend_item, "friend_userid");
                if(f_userid != NULL && cJSON_IsString(f_userid) && strlen(f_userid->valuestring) > 0) {
                    strncpy(friendList->friends[i].friend_userid, f_userid->valuestring,
                            sizeof(friendList->friends[i].friend_userid) - 1);
                    friendList->friends[i].friend_userid[sizeof(friendList->friends[i].friend_userid) - 1] = '\0';
                }

                // 解析好友头像
                cJSON * avatar = cJSON_GetObjectItem(friend_item, "friend_avatar");
                if(avatar != NULL && cJSON_IsString(avatar) && strlen(avatar->valuestring) > 0) {
                    strncpy(friendList->friends[i].friend_avatar, avatar->valuestring,
                            sizeof(friendList->friends[i].friend_avatar) - 1);
                    friendList->friends[i].friend_avatar[sizeof(friendList->friends[i].friend_avatar) - 1] = '\0';
                }
            }
        }
    }

    cJSON_Delete(root);
}

void get_friend_list()
{
    if(user_event.userid == NULL || strlen(user_event.userid) == 0) {
        printf("未登录\n");
        return ;
    }

    cJSON * root = cJSON_CreateObject();
    if(root == NULL) {
        printf("错误：创建 JSON 根对象失败\n");
        return ;
    }

    cJSON_AddStringToObject(root, "type", "get_friendList");

    cJSON * payload = cJSON_CreateObject();
    if(payload == NULL) {
        printf("错误：创建 payload 子对象失败\n");
        cJSON_Delete(root);
        return ;
    }

    cJSON_AddStringToObject(payload, "userid", user_event.userid);
    cJSON_AddItemToObject(root, "payload", payload);

    char * json_str = cJSON_PrintUnformatted(root);
    if(json_str == NULL) {
        printf("错误:JSON 转换为字符串失败\n");
        cJSON_Delete(root);
        return ;
    }

    cJSON_Delete(root);

    send_message_to_server(&server_info, json_str);
}